"""
音频轨道例子的UI层。
"""
import typing

from elio import core


class TrackLayer(core.AutoRecycleLayer[core.Activity]):
    async def on_create(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_create(*args, *kwargs)

    async def on_hide(self):
        await super().on_hide()

    async def on_show(self):
        await super().on_show()
        activity = self.parent
        # AudioTrack组件测试
        import wave
        with wave.open('test.wav') as f:
            sample_rate, channels = f.getframerate(), f.getnchannels()
            track = await core.AudioTrack.create(activity, sample_rate, channels)
            await track.set_volume(1, 1)
            await track.play()
            # 写入一次最多支持0.06秒，用时间*采样率可以算出每次写入的帧数
            n_frames = int(sample_rate * 0.06)
            data = f.readframes(n_frames)
            while data:
                res = await track.write(data, n_frames)
                data = f.readframes(n_frames)
        await track.destroy()
        await activity.pop_layer()

    async def on_pause(self):
        await super().on_pause()

    async def on_resume(self):
        await super().on_resume()

    async def on_destroy(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_destroy(*args, **kwargs)
